//
//  CustomBar.m
//  UI Demo
//
//  Created by Rainy Zou on 15/11/26.
//  Copyright © 2015年 Rainy Zou. All rights reserved.
//


#import "CustomBar.h"

@interface CustomBar()

@property (nonatomic, weak) UIButton *selectBtn;

@end

@implementation CustomBar

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)initWithFrame:(CGRect)frame
{
    NSLog(@"----%@",NSStringFromCGRect(frame));
    if (self == [super initWithFrame:frame]) {
       
        NSLog(@"----%@",NSStringFromCGRect(self.frame));
        [self setupBtns];
    }
    return self;
}

-(void)setupBtns{

    //自定义的tabbar添加5个按钮
    for (NSInteger i = 0; i < 5; i++) {
        // 获取普通状态的图片名称
        NSString *normalImg = [NSString stringWithFormat:@"bar%ld_normal", i+1];

        // 获取选中的图片
        NSString *selImg = [NSString stringWithFormat:@"bar%ld_selected", i + 1];

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:normalImg] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:selImg] forState:UIControlStateSelected];


        //监听事件
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        //绑定tag
        btn.tag = i;
        
        [self addSubview:btn];
    }
   NSLog(@"----%@",NSStringFromCGRect(self.frame));

}

- (void)btnClick:(UIButton *)button
{
    if ([self.delegete respondsToSelector:@selector(btnClick:from:to:)]) {
        [self.delegete btnClick:self from:self.selectBtn.tag to:button.tag];
    }
    
    self.selectBtn.selected = NO;
    
    button.selected = YES;
    
    self.selectBtn = button;
    
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    NSInteger count = self.subviews.count  ;
    //布局子控件
    //按钮宽度与高度
    CGFloat btnW = self.bounds.size.width /count;
    CGFloat btnH = self.bounds.size.height;
    
    int j = 0;
    //自定义的tabbar添加5个按钮
        for (NSInteger i = 0; i < count; i++) {
    
            if([self.subviews[i] isKindOfClass:[UIButton class]]){
            //获取btn
            UIButton *btn = self.subviews[i];
    
            //设置按钮的frm
            btn.frame = CGRectMake(btnW * j, 0, btnW, btnH);
            j++;
            }
    
        }
}

@end
